package com.she.iiicoursecenter.manager;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Handler;

public class AsyncImageLoader {
	private static AsyncImageLoader mAsyncImageLoader;
	public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();

	private ExecutorService executorService = Executors.newFixedThreadPool(3);
	private final Handler handler = new Handler();

	public static AsyncImageLoader getInstance() {
		if(mAsyncImageLoader == null) {
			mAsyncImageLoader = new AsyncImageLoader();
		}
		return mAsyncImageLoader;
	}

	public void clearAllCache() {
		synchronized (imageCache) {
			Set<Entry<String, SoftReference<Drawable>>> set = imageCache.entrySet();
			Object[] objArr = set.toArray();
			for(int i=0; i<objArr.length; i++) {
				@SuppressWarnings("unchecked")
				Entry<String, SoftReference<Drawable>> entry = (Entry<String, SoftReference<Drawable>>)objArr[i];
				Drawable bitmap = entry.getValue().get();
				if(bitmap != null) {
					//
					bitmap.setCallback(null);
//					if(!bitmap.get.isRecycled()) bitmap.recycle();
					bitmap = null;
				}
			}
			imageCache.clear();
			System.gc();
		}
	}

	/**
	 * 記得要在Mainifest加入ACCESS_NETWORK_STATE權限
	 * 
	 * @param imageUrl
	 *            圖片URL
	 * @param imageCallback
	 *            callback
	 */
	public Drawable loadDrawable(final Context context, final String imageUrl,
			final ImageCallback1 imageCallback) {

		if (imageCache.containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = imageCache.get(imageUrl);
			if (softReference.get() != null) {
				System.out.println("using softReference~!~");
				return softReference.get();
			}
		}
		if (HttpUtils.is_Intent(context)) {
			executorService.submit(new Runnable() {
				public void run() {
					try {
						final Drawable drawable = HttpUtils.loadImageFromUrl(imageUrl);
						if (drawable != null) {
							imageCache.put(imageUrl,new SoftReference<Drawable>(drawable));
							handler.post(new Runnable() {
								public void run() {
									imageCallback.imageLoaded(drawable,
											imageUrl);
								}
							});
						}
					} catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			});
		}
		return null;

	}

	// callback interface
	public interface ImageCallback1 {
		public void imageLoaded(Drawable imageDrawable, String imageUrl);
	}
}
